package com.hrsaas.ext.spider.handler;

import java.io.IOException;

import com.google.common.net.MediaType;
import com.hrsaas.ext.spider.core.ResponseHandler;
import com.hrsaas.ext.spider.util.JsonUtils;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * <p>
 * 功能：默认的 response handler,实现困难，有问题
 * <p>
 * @author wangxiaoliang@kanzhun.com
 *
 * 2018年8月2日
 */
@Deprecated
public abstract class DefaultResponseHandler<T> extends ResponseHandler<T> {

	/**
	 * 转换响应数据到实体对象
	 * @param mediaType
	 * @param content
	 * @return
	 * @throws IOException 
	 */
	@Override
	protected Object convert(HttpResponseStatus status, HttpHeaders headers, byte[] content) {
		MediaType mediaType = null;
		if (headers.contains(HttpHeaderNames.CONTENT_TYPE)) {
			try {
				mediaType = MediaType.parse(headers.get(HttpHeaderNames.CONTENT_TYPE));
			} catch (Exception ex) {
				// do nothing
			}
		}	
		Class<T> type = getType();
		// if content type is json,convert json to type
		if (MediaType.JSON_UTF_8 == mediaType) {
			return JsonUtils.fromJson(getConent(content), type);
		}
		else if (MediaType.ANY_TEXT_TYPE == mediaType){
			return getConent(content);
		}
		else {
			throw new NoSuchMethodError("response no content_type ,so convert...");
		}
	}

}
